/*
 * Copyright (C) 冷锋
 */
#include "timeevent.h"

struct timeval		g_StartTime ={0,0};
int	g_iTimerID = 0;
//计算时间差
void SetStartTime()
{
	gettimeofday(&g_StartTime,NULL);
}
void TimevalSub(struct timeval* tv1,struct timeval* tv2,struct timeval* r)
{
	r->tv_sec = tv1->tv_sec-tv2->tv_sec;
	r->tv_usec = tv1->tv_usec-tv2->tv_usec;

}

int GetRunningTime()
{
	timeval now;
	gettimeofday(&now,NULL);
	timeval sub;
	TimevalSub(&now,&g_StartTime,&sub);
	return sub.tv_sec*1000+sub.tv_usec/1000;
}

void TimevalDelay(int delay,struct timespec*absTime)//单位毫秒
{
	timeval now;
	gettimeofday(&now,NULL);
	timeval add;
	timeval res;
	add.tv_sec = delay/1000;
	add.tv_usec = (delay%1000)*1000;
	
	timeradd(&now,&add,&res);
	absTime->tv_sec = res.tv_sec;
	absTime->tv_nsec =res.tv_usec*1000;
}
CTimeEvent::CTimeEvent(int msec,cbTimeOut cbFunc,void*arg)
{
	m_cbTimeFunc = cbFunc;
	m_pArg = arg;
	m_iTimeout = msec + GetRunningTime();
	m_ID = g_iTimerID++;
}

void CTimeEvent::Call()
{
	if (m_cbTimeFunc)
	{
		m_cbTimeFunc(m_pArg);
	}
}

int CTimeEvent::GetTimeOut()
{
	return m_iTimeout;
}
int CTimeEvent::Cmp(CTimeEvent*a,CTimeEvent*b)
{ 
	if (a->m_iTimeout<b->m_iTimeout)return -1;
	if (a->m_iTimeout>b->m_iTimeout)return 1;
	if (a->m_iTimeout==b->m_iTimeout)return 0;
}

int CTimeEvent::GetID()
{
	return m_ID;
}